package com.drinks.yiniang.adapter.banner;

import android.content.Context;
import android.view.View;

import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.comment.BannerEntity;
import com.drinks.yiniang.utils.GlideUtils;
import com.hansen.library.adapter.BaseRecyclerBannerAdapter;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.hansen.library.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author han
 * @date 2019/12/17
 */
public class BannerRecyclerAdapter extends BaseRecyclerBannerAdapter<BannerRecyclerAdapter.ViewHolder> {

    private Context mContext;

    private List<BannerEntity> mBannerData;

    public BannerRecyclerAdapter(Context context) {
        super(context);
        this.mContext = context;
        this.mBannerData = new ArrayList<>();
    }

    @Override
    public int getItemCountReal() {
        return CommonUtils.getListSize(mBannerData);
    }

    @Override
    public int getItemCount() {
        // 如果设置为 Integer.MAX_VALUE 则会和 ViewPager 产生左右滑动冲突，具体原因未知
        // 1. 设置为 3000000(这个数值可自行测试得出) ，不用自定义 RecyclerView ；
        // 2. 自定义 RecyclerView 重写 dispatchTouchEvent 方法， 调用 getParent().requestDisallowInterceptTouchEvent(true) ，这样就可以设置为 Integer.MAX_VALUE 。
        // 详情访问：https://juejin.im/post/5d0c7693f265da1b6a349c5f
        int count = getItemCountReal();
        return count <= 1 ? count : Integer.MAX_VALUE;
    }

    @Override
    public BannerEntity getItem(int position) {
        return CommonUtils.isArrayIndexOutOfBounds(mBannerData, position % getItemCountReal()) ? null : mBannerData.get(position % getItemCountReal());
    }

    @Override
    public int getViewResourceId(int viewType) {
        return R.layout.item_home_banner;
    }

    @Override
    public ViewHolder getViewHolder(View view, int viewType) {
        return new ViewHolder(view);
    }

    @Override
    public void setView(final ViewHolder holder, final int position) {
        GlideUtils.loadBannerImage(mContext, holder.iv_home_banner, getItem(position % getItemCountReal()).getCover_url());
    }

    public List<BannerEntity> getBannerData() {
        return mBannerData;
    }

    public void addBannerData(List<BannerEntity> bannerData) {
        if(mBannerData == null) {
            mBannerData = new ArrayList<>();
        }

        mBannerData.clear();

        if(bannerData != null) {
            this.mBannerData.addAll(bannerData);
        }
    }

    class ViewHolder extends BaseRecyclerBannerAdapter.ViewHolder {

        RatioRoundImageView iv_home_banner;

        ViewHolder(View itemView) {
            super(itemView);

            iv_home_banner = itemView.findViewById(R.id.iv_home_banner);
        }
    }
}